import type { ElegantConstRoute } from '@soybean-react/vite-plugin-react-router';
import type { RouteObject } from 'react-router-dom';

import { transformElegantRoutesToReactRoutes } from '../elegant/transform';

export const getReactRoutes = (route: ElegantConstRoute[]) => {
  return transformElegantRoutesToReactRoutes(route);
};

function isGroup(id?: string) {
  if (!id) return false;
  return id.startsWith('(') && id.endsWith(')');
}

export function filterRoutes(
  routes: RouteObject[],
  parent: string | null = null,
  authRoutes: Router.SingleAuthRoute[] = [],
  cacheRoutes: string[] = [],
  parentPath: string = '',
) {
  return routes.reduce((acc, route) => {
    const noPermission = route.handle?.constant;

    const newRoute = { ...route };

    const isRouteGroup = isGroup(route.id);

    if (newRoute.handle?.keepAlive) {
      cacheRoutes.push(route.path || '');
    }

    if (newRoute.children && newRoute.children.length > 0) {
      newRoute.children = filterRoutes(newRoute.children, route.id, authRoutes, cacheRoutes, route.path);
    }

    if (!noPermission) {
      if (isRouteGroup || newRoute.children?.[0]?.index) {
        const children = newRoute.children
          ?.map((child) => {
            if (child.handle?.constant || isGroup(child.id) || child.children?.[0]?.index) {
              return child;
            }
            return null;
          })
          .filter(Boolean) as RouteObject[];
        newRoute.children = children;
        acc.push(newRoute);
      } else {
        authRoutes.push({
          parent,
          parentPath,
          route: newRoute,
        });
      }
    } else {
      acc.push(newRoute);
    }

    return acc;
  }, [] as RouteObject[]);
}
